package com.whg.demo;

import com.google.common.util.concurrent.RateLimiter;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @Author whg
 * @create 2022/12/1 11:33
 * @description：
 */
@SpringBootTest(classes = ProjectTwoApplication.class)
public class SpringBootTestDemo {

    @Test
    public void testOne(){
        System.out.println("test one");
        Assert.isTrue(1 == 1,"不相等");
    }

    @Test
    public void testTwo(){
        System.out.println("test two");
    }

    //@BeforeAll注解在静态方法上(启动的时候加载)，@BeforeEach注解在非静态方法上
    @BeforeEach
    public void testBefore(){
        System.out.println("before");
    }

    //@AfterAll注解在静态方法上，@AfterEach注解在非静态方法上
    @AfterEach
    public void testAfter(){
        System.out.println("after");
    }

    @BeforeAll
    public static void testBefore2(){
        //启动的时候就会打印
        System.out.println("before2");
    }

    @AfterAll
    public static void testAfter2(){
        System.out.println("after2");
    }

    @Test
    public void rateLimiter(){
        CountDownLatch countDownLatch = new CountDownLatch(30);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        RateLimiter limiter = RateLimiter.create(5);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 30; i++) {
            int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    double time = limiter.acquire();
                    long after = System.currentTimeMillis() - start;
                    System.out.println(format.format(new Date()) + ":第" + finalI + "个请求等待:" + time + "，已开始" + after + "毫秒");
                    countDownLatch.countDown();
                }
            }).start();
        }
        while (true){
            if (countDownLatch.getCount() == 0){
                System.out.println("total time：" + (System.currentTimeMillis() - start));
                break;
            }
        }
    }

    @Test
    public void rateLimiter2(){
        CountDownLatch countDownLatch = new CountDownLatch(10);
        RateLimiter limiter = RateLimiter.create(10);
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("before pass");
                    limiter.acquire();
                    System.out.println("pass");
                    countDownLatch.countDown();
                }
            }).start();
        }
        while (true){
            if (countDownLatch.getCount() == 0){
                System.out.println("finish");
                break;
            }
        }
    }
}
